package com.ethink.gateway.handler;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ethink.framework.common.constant.CommonRespCode;
import com.ethink.framework.common.exception.BusinessException;
import com.ethink.framework.common.jwt.JwtPayload;
import com.ethink.framework.common.jwt.JwtUtils;
import com.ethink.framework.common.web.context.RequestEntityType;
import com.ethink.gateway.model.RequestEntityRule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.AntPathMatcher;

/**
 * @Author Allen(Tel : mobile)
 * @Date 2020-06-11 10:03
 **/
@Slf4j
public abstract class RequestHandler {

    protected AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 处理请求
     *
     * @param httpServletRequest
     * @param requestEntityRule
     */
    public abstract ServerHttpRequest handler(ServerHttpRequest httpServletRequest, RequestEntityRule requestEntityRule);

    /**
     * jwt 验证，签名，是否过期，主题是否一致
     *
     * @param token
     * @param requestEntityType
     * @return
     */
    protected JwtPayload jwtTokenValidate(String token, RequestEntityType requestEntityType) {
        // header 中token 非空
        if (StringUtils.isBlank(token)) {
            throw new BusinessException(CommonRespCode.NOT_LOGIN);
        }
        // jwt 验证，签名，是否过期，主题是否一致
        JwtPayload jwtPayload;
        try {
            DecodedJWT decodedJWT = JwtUtils.verify(token, requestEntityType.toString());
            return JSON.parseObject(Base64.decodeStr(decodedJWT.getPayload()), JwtPayload.class);
        } catch (Exception e) {
            log.error("jwt 验证失败", e);
            throw new BusinessException(CommonRespCode.NOT_LOGIN);
        }
    }
}
